//
//  YBMineVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/5.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import HandyJSON
import EachNavigationBar
import SVProgressHUD

class YBMineVC: BaseVC {
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    enum RowType {
        case activationCode
        case inviteRewards
        case setting
        case userGroup
        case agreement
        case privacy
        case helpCenter
        case logout
        
        var style: (icon: String, des: String) {
            switch self {
            case .activationCode: return ("icon_mine_activationcode", "激活码兑换")
            case .inviteRewards: return ("icon_mine_inviterewards", "邀请有奖")
            case .setting: return ("icon_mine_setting", "系统设置")
            case .userGroup: return ("icon_mine_usergroup", "用户交流群")
            case .agreement: return ("icon_mine_agreement", "酷卡云手机服务协议")
            case .privacy: return ("icon_mine_privacy", "酷卡云云手机隐私政策")
            case .helpCenter: return ("icon_mine_helpcenter", "帮助中心")
            case .logout: return ("icon_mine_logout", "注销账号")
            }
        }
    }

    private var rows: [RowType] = [.setting, .userGroup, .agreement, .privacy, .helpCenter, .logout]

    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigation.bar.alpha = 0
        navigation.item.title = "个人中心"
        navigation.bar.barTintColor = ColorDef.dark27
        self.bk_naviBarTitleColor(color: .white)

        view.backgroundColor = .lightWhiteDark27
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(-kNavigationBarHeight)
        }

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.bk_setBackBarButtonItem(isHidden: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.bk_setPopSwipe(false)
    }
    
    // MARK: - lazy
    lazy var vm: YBMineViewModel = {
        let vm = YBMineViewModel()
        return vm
    }()
    
    private lazy var tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .plain)
        tv.backgroundColor = .clear
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.separatorStyle = .none
        tv.delegate = self
        tv.dataSource = self
        tv.showsVerticalScrollIndicator = false
        tv.bk_setHeaderFooter(headerV: tableHeader, footerV: tableFooter)
        tv.register(cellWithClass: YBMineCell.self)
        return tv
    }()
    
    private lazy var tableHeader: YBMineTableHeader = {
        let header = YBMineTableHeader()
        header.delegate = self
        return header
    }()
    
    private lazy var tableFooter: YBMineTableFooter = {
        let footer = YBMineTableFooter()
        footer.onLogout = { [weak self] in
            guard let self = self else { return }
            let alertController = UIAlertController(title: "提示", message: "确定退出当前登录？", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "确定", style: .default) { _ in
                PPP("用户点击了确定按钮")
                self.vm.req_CloseSSE { ok, obj, msg, code in
                    if ok {
                        HintTool.toast("退出成功")
                    }
                }
                AppHelper.startLogout()
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
                 PPP("用户点击了取消按钮")
            }
            alertController.addAction(okAction)
            alertController.addAction(cancelAction)
            
            VisibleCtrl?.present(alertController, animated: true)
        }
        return footer
    }()
    
}

// MARK: - YBMineTableHeaderDelegate
extension YBMineVC: YBMineTableHeaderDelegate {
    
    func onTableHeaderDidClick(itemType: YBMineTableHeader.ItemType) {
        switch itemType {
        case .avatar:
            break
        case .personalInfo:
            let vc = YBMinePersonalInfoVC()
            self.navigationController?.pushViewController(vc)
        }
    }
    
    func onTableHeaderDidSelect(stackType: YBMineTableHeader.StackType) {
        switch stackType {
        case .order:
            let vc = YBMineOrderVC()
            self.navigationController?.pushViewController(vc)
        case .device:
            let vc = YBCloudComputerVC(viewType: .center)
            self.navigationController?.pushViewController(vc)
        case .useRecord:
            let vc = YBMineUseRecordVC()
            self.navigationController?.pushViewController(vc)
        }
    }
    
}

// MARK: - UITableView代理
extension YBMineVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YBMineCell.self, for: indexPath)
        let row = rows[indexPath.row]
        cell.updateCell(by: row)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let row = rows[indexPath.row]
        switch row {
        case .activationCode:
            let vc = YBMineActivationCodeVC()
            self.navigationController?.pushViewController(vc)
        case .inviteRewards:
            let vc = YBMineInviteVC()
            self.navigationController?.pushViewController(vc)
        case .setting:
            let vc = YBMineSettingVC()
            self.navigationController?.pushViewController(vc)
        case .userGroup:
            let vc = YBMineUserGroupPopupVC()
            self.present(vc, animated: true)
        case .agreement:
            let vc = BKWebViewVC(with: "https://superkuka.com/service-agreement-kuka.html")
            self.navigationController?.pushViewController(vc)
        case .privacy:
            let vc = BKWebViewVC(with: "https://superkuka.com/privacy-policy-kuka.html")
            self.navigationController?.pushViewController(vc)
        case .helpCenter:
            let vc = BKWebViewVC(with: "https://superkuka.com/privacy-policy-kuka.html")
            self.navigationController?.pushViewController(vc)
        case .logout:
            do {
                let alertController = UIAlertController(title: "温馨提示", message: "您正在进行注销操作！确定注销当前用户？", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "确定", style: .default) { _ in
                    PPP("用户点击了确定按钮")
                    AppHelper.startLogout()
                }
                let cancelAction = UIAlertAction(title: "取消", style: .cancel) { _ in
                    PPP("用户点击了取消按钮")
                }
                
                alertController.addAction(okAction)
                alertController.addAction(cancelAction)
                VisibleCtrl?.present(alertController, animated: true)
            }
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        tableHeader.scrollViewDidScroll(contentOffsetY: offsetY)
        self.bk_changeNaviBarAnimate(offsetY <= -kNavigationBarHeight/2)
    }
    
}
